function initEvn() {
	var cWidth = document.body.clientWidth - 100;
	var cHeight = document.body.clientHeight ;
	var tmpW = Math.ceil(cWidth/curLevel) ;
	var tmpH = Math.ceil(cHeight/curLevel) ;
	norWH = tmpW > tmpH?tmpH:tmpW ;
	//设置字体大小
	document.getElementsByTagName("body")[0].style.fontSize = Math.ceil(norWH/3) + "px" ;
	document.getElementById("levelSel").style.fontSize = Math.ceil(norWH/3) + "px" ;
	document.getElementById("levelSel").style.height = (Math.ceil(norWH/3)+5) + "px" ;
	document.getElementById("levelSel").style.width = (Math.ceil(norWH/3)+30) + "px" ;
}

// 等级选择
function selectLevel() {
	foucusId = "" ;
	var obj = document.getElementById("levelSel") ;
	curLevel = obj.value ;
	document.getElementById("sdDiv").innerHTML = "" ;
	document.getElementById("sdValue").innerHTML = "" ;
	initEvn() ;
	console.log("norWH====>>>" + norWH) ;
	initSDDiv(curLevel) ;
	initSDValue(curLevel) ;
}
// 字母点击事件
function numClick(event,id) {
	var divObj = document.getElementById(id) ;
	divObj.focus() ;
	event = event || window.event;
	if(document.getElementById(foucusId)) {
		document.getElementById(foucusId).classList.remove("sdfocus") ;
	}
	var focusedElement = document.getElementById(id) ;
	if(focusedElement.getAttribute("isFixed")=="true") {
		foucusId = id ;
		document.getElementById(foucusId).classList.add("sdfocus") ;
	}
	// 阻止事件
	//event.preventDefault();
}

// 生成min~max的随机数
function getRandomNum(max,min) {
	return Math.floor(Math.random()*(max-min+1)+min) ;
}

// 是否可以添加数字
function canAddNum(row,col,num,sourceAry) {
	var rowAry = sourceAry[row] ;
	var colAry = [] ;
	for(var i=0;i<row;i++){
		colAry.push(sourceAry[i][col]) ;
	}
	for(var i=0;i<rowAry.length;i++) {
		if(rowAry[i]==num) return false ;
	}
	for(var i=0;i<colAry.length;i++) {
		if(colAry[i]==num) return false ;
	}
	return true ;
}
// 添加默认值
function addDefaultNum(row, col, sourceAry) {
	var num = getRandomNum(sourceAry.length,1) ;
	var flag = canAddNum(row,col,num,sourceAry) ;
	if(flag) {
		sourceAry[row][col] = num ;
	} else {
		sourceAry[row][col] = 0 ;
	}
}

//初始化数独DIV
function initSDDiv(size) {
	var len = size * size ;
	sourceAry = new Array(size) ;
	for(var row = 0;row < size;row++) {
		sourceAry[row] = new Array(size);
		for(var col = 0;col < size;col++) {
			var flag = getRandomNum(size,1) === 1?true:false ;
			// 添加默认值
			if(flag) {
				addDefaultNum(row,col,sourceAry) ;
			} else {
				sourceAry[row][col] = 0;
			}
		}
	}
	var sdDiv = document.getElementById("sdDiv") ;
	sdDiv.style.width = norWH * size + "px"; 
	sdDiv.style.height = norWH * size + "px";
	for(var i=0;i<size*size;i++) {
		// 当前行
		var curRow = Math.floor(i / size) ;
		// 当前列
		var curCol = i % size ;
		var curNum = sourceAry[curRow][curCol] ;
		var ndiv = document.createElement("div");
		ndiv.id = "child_"+i;
		if(curNum == 0 ) {
			ndiv.setAttribute("isFixed",true);
			//ndiv.setAttribute("contenteditable",true);
		} else {
			ndiv.style.color = "red";
			ndiv.innerText = curNum ;
		}
		ndiv.setAttribute("class","sdItem") ;
		ndiv.style.width = (norWH - 5)+"px" ;
		ndiv.style.height = (norWH - 5)+"px" ;
		ndiv.setAttribute("onClick","numClick(event,'"+ndiv.id+"')");
		sdDiv.appendChild(ndiv);  
	}
}

function mouseDownHandler(event,id) {
	event = event || window.event;
	event.preventDefault();
	var divObj = document.getElementById(id) ;
	var num = divObj.innerText ;

	var focusedElement = document.getElementById(foucusId);
	if(focusedElement.getAttribute("isFixed")=="true"){
		focusedElement.innerText = num ;
	}
}
// 初始化底部
function initSDValue(size) {
	var sdValue = document.getElementById("sdValue") ;
	sdValue.style.width = norWH * size + "px"; 
	sdValue.style.height = norWH + "px";
	for(var i = 0; i < size; i++) {
		var ndiv = document.createElement("div");
		ndiv.id = "value_"+i;
		ndiv.setAttribute("class","sdItem") ;
		ndiv.style.width = (norWH - 5)+"px" ;
		ndiv.style.height = (norWH - 5)+"px" ;
		ndiv.setAttribute("onMouseDown","mouseDownHandler (event,'"+ndiv.id+"')");
		ndiv.innerText = i+1 ;
		sdValue.appendChild(ndiv);  
	}
}

function answer() {
	var source = new Array() ;
	for(var i=0;i<curLevel;i++){
		var cItem = new Array() ;
		source.push(cItem) ;
		for(var j=0;j<curLevel;j++){
			cItem.push(createSdItem(curLevel,sourceAry[i][j])) ;
		}
	}
	change(source,0) ;
	var itemAry = document.getElementById("sdDiv").getElementsByTagName("div");
	for(var i=0;i<itemAry.length;i++) {
		// 当前行
		var curRow = Math.floor(i / curLevel) ;
		// 当前列
		var curCol = i % curLevel ;
		itemAry[i].innerText = source[curRow][curCol].value ;
	}
	//printAry(source);
}

// 提交
function submit() {
	var itemAry = document.getElementById("sdDiv").getElementsByTagName("div");
	var map = new Array(curLevel) ;
	for(var i=0;i<curLevel;i++) {
		map[i] = 0 ;
	}
	for(var i=0;i<itemAry.length;i++) {
		var val = itemAry[i].innerText 
		if(val!='') {
			map[val-1] = map[val-1] + 1 ;
		}
	}
	// 为true表示挑战成功，为false表示挑战失败
	var flag = true ;
	for(var i=0;i<curLevel;i++) {
		if(map[i] != curLevel) {
			flag = false ;
			break ;
		}
	}
	//挑战成功
	if(flag) {
		var res = window.confirm("挑战成功,继续挑战吗?") ;
		if(res) {
			if(curLevel < 9) {
				curLevel = parseInt(curLevel) + 1 ;
				document.getElementById("levelSel_"+curLevel).selected = true ;
			}
			selectLevel() ;
		}
	} else {
		var res = window.confirm("胜败乃兵家常事，继续挑战?") ;
		if(res) {
			selectLevel() ;
		}
	}
}

// 刷新
function refresh() {
	try{
		selectLevel() ;

		var source = new Array() ;
		for(var i=0;i<curLevel;i++){
			var cItem = new Array() ;
			source.push(cItem) ;
			for(var j=0;j<curLevel;j++){
				cItem.push(createSdItem(curLevel,sourceAry[i][j])) ;
			}
		}
		change(source,0) ;

	}catch(e){
		console.log("无解...需要重新出题目!!!!!!") ;
		refresh();
	}
}



function createSdItem(size) {
    var list = new Array();
    for (var i = 0; i < size; i++) {
        list.push(i+1) ;
    }
    return {
        list:list,
        value:0,
        canDel:true
    }
}

function createSdItem(size, num) {
    var list = new Array();
    var canDel = true ;
    for (var i = 0; i < size; i++) {
        var tmp = i+1 ;
        if(tmp!=num) {
            list.push(tmp) ;
        } else {
            canDel = false ;
        }
    }
    return {
        list:list,
        value:num,
        canDel:canDel
    }
}

function checkNum(row, col, num, source) {
    var rowAry = source[row] ;
    var colAry = new Array() ;
    for(var i=0;i<rowAry.length;i++) {
        colAry.push(source[i][col]) ;
    }
    for(var i=0;i<rowAry.length;i++) {
        if(rowAry[i].value==num) return false ;
    }
    for(var i=0;i<colAry.length;i++) {
        if(colAry[i].value==num) return false ;
    }
    return true ;
}

function getOldIndex(source, curIndex) {
    var oldIndex = curIndex -1;
    for(;oldIndex>=0;oldIndex--) {
        var row = Math.floor(oldIndex/source.length) ;
        var col = oldIndex% source.length ;
        if(source[row][col].canDel)
            return oldIndex ;
    }
    return oldIndex ;
}

function change(source, curIndex) {
    var len = source.length ;
    if(curIndex>=len*len)
        return;
    // 当前行
    var curRow = Math.floor(curIndex / len) ;
    // 当前列
    var curCol = curIndex % len ;

    var sdItem = source[curRow][curCol] ;
    //不可删除(跳过)
    if(!source[curRow][curCol].canDel) {
        change(source,curIndex+1);
        return;
    }


    var tmpItem = source[curRow][curCol] ;
    var curList = tmpItem.list ;
    var flag = false ;
    var curNum = 0 ;
    var listIndex = 0 ;
    for (; listIndex < curList.length; listIndex++) {
        curNum  = curList[listIndex] ;
        flag = checkNum(curRow,curCol,curNum,source) ;
        if(flag) break;
    }
    // 可以添加
    if(flag) {
        curList.splice(listIndex,1) ;
        source[curRow][curCol].value = curNum;
        change(source,curIndex+1);
    }
    // 回退
    else{
        var nList = new Array() ;
        for(var i=0;i<len;i++)
            nList.push(i+1) ;
        source[curRow][curCol].value = 0;
        source[curRow][curCol].list = nList;

        var oldIndex = getOldIndex(source,curIndex) ;
        if(oldIndex < 0) {
            console.log("无解!!!!");
            //return;
			throw 'no answer';
        }
        // 当前行
        var oldRow = Math.floor(oldIndex / len) ;
        // 当前列
        var oldCol = oldIndex % len ;
        var oldNum = source[oldRow][oldCol].value ;
        var oldList = source[oldRow][oldCol].list ;
        for (var i=0;i<oldList.length;i++) {
            if(oldList[i]==oldNum) {
                oldList.remove(i) ;
                break;
            }
        }
        source[oldRow][oldCol].value = 0;

        change(source, oldIndex) ;
    }

}

function printAry(source){
    for(var i=0;i<source.length;i++){
        var rowAry = source[i] ;
        var line = "" ;
        for(var j=0;j<rowAry.length;j++){
            line=line+rowAry[j].value+", ";
        }
    }
}